package com.xying.util;

import com.xying.common.ResponseCode;
import com.xying.common.ServerResponse;

import com.xying.pojo.Usr;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Hisen
 * @date 2017/11/8
 */
public class ValidateUtil {

  public static ServerResponse validate(Object... data){
    for (Object o : data){
      if (o == null) {
        return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
      }
      if(o instanceof String) {
        ServerResponse serverResponse = validateString(o);
        if (!serverResponse.isSuccess()) { return serverResponse; }
      }
      if (o instanceof List) {
        ServerResponse serverResponse = validateList((List) o);
        if (!serverResponse.isSuccess()) {
          return serverResponse;
        }
      }
    }
    return ServerResponse.createBySuccess();
  }

  private static ServerResponse validateString(Object oString){
    if ("".equals(oString)) {
      return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
    }
    return ServerResponse.createBySuccess();
  }

  private static ServerResponse validateList(List oList){
    if (CollectionUtils.isEmpty(oList)) {
      return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getDesc());
    }
    return ServerResponse.createBySuccess();
  }

  public static ServerResponse validateNormalLogin(HttpServletRequest request){
    Usr usr = (Usr) request.getSession().getAttribute(request.getSession().getId());
    if (usr == null || !StringUtils.isNotEmpty(usr.getIdNo())){
      return ServerResponse.createByErrorMessage("用户未登录");
    }

    return ServerResponse.createBySuccess(usr);
  }
}
